package com.sms.util;

import java.sql.Connection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sms.db.DBOperator;
import com.sms.po.TTask;

public abstract class Tools_MXF extends Tools_HZX{

	private static final Log logger = LogFactory.getLog(Tools_MXF.class);
	
	/**
	 * 扣量函数(任务有效记录数>3000才自动扣量),白名单、非法短信不在扣量范围内
	 * 有效记录数>3000
	 * @param task
	 * @param discountStr
	 * @return 返回实际扣成功数量
	 */
	public static int discountTask(TTask task,String discountStr) throws Exception{
		if(discountStr==null || "".equals(discountStr.trim()))
			return 0;
		if(task.getTotals()<3000)//小于3000，不扣量
			return 0;
		if("0".equals(task.getStatus()))
			throw new Exception("只能对待审核的任务进行扣量");
		
		String sql;
		int discountCount=0;//扣量数量
		int totals=task.getTotals();
		Connection conn = null;
		try{
			discountStr=discountStr.replaceAll("\\%", "");
			String[] strArr=discountStr.split("\\;");
			//由于扣量用到临时表,事务在此处不起作用,所以需对扣量字符串进行预先转换检测是否有错
			for(String str:strArr){
				String[] strArr2=str.split("~");
				Double startRow=totals*Double.parseDouble("0."+strArr2[0]);
				Double endRow=totals*Double.parseDouble("0."+strArr2[1]);
			}
			
			conn=DBOperator.getConnection();
			for(String str:strArr){
				String[] strArr2=str.split("~");
				Double startRow=totals*Double.parseDouble("0."+strArr2[0]);
				Double endRow=totals*Double.parseDouble("0."+strArr2[1]);
				sql="UPDATE t_waitsend SET sendflag='0' WHERE id IN(" +
						"SELECT tmp.id FROM (SELECT * FROM t_waitsend WHERE and status='0'" 
						+" and task_id="+task.getId()
						+" LIMIT "+startRow.intValue()+","+endRow.intValue()+")tmp)";
				System.out.println("扣量sql="+sql);
				discountCount+=conn.createStatement().executeUpdate(sql);
			}
			//更新白名单不在扣量范围内
			sql="UPDATE t_waitsend SET sendflag='1' WHERE task_id="+task.getId()
				+" and (user_id,phone) IN (SELECT user_id,phone FROM whitelist)";
			System.out.println("扣量sql="+sql);
			int count2=conn.createStatement().executeUpdate(sql);
			return discountCount-count2;
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("扣量失败",e);
		}finally{
			DBOperator.closeConnection(conn);
		}
	}
}
